/**
 * Created by luzd on 17/3/10.
 */
var requestAnimationFrame = window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function (callback) {
        setTimeout(callback, 1000 / 60);
    };
var cancelAnimationFrame = window.cancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.webkitCancelAnimationFrame ||
    window.msCancelAnimationFrame ||
    window.oCancelAnimationFrame;
var zan = {};
$(function () {
    new Swiper('.swiper-container', {
        initialSlide: 1,
        onInit: function () {
            $('.scene').css('opacity', 1);
        }
    });
    $('#linkBtn').click(function () {
        $('.interactive,.brand').addClass('hide');
        $('.p_list,.cover').removeClass('hide');
        setTimeout(function () {
            $('.p_list').addClass('active');
        }, 0);
    });
    $('.cover').click(function () {
        $('.p_list').removeClass('active');
        setTimeout(function () {
            $('.interactive,.brand').removeClass('hide');
            $('.p_list,.cover').addClass('hide');
        }, 400);
    });
    /**
     * 关闭直播页面
     */
    $('#closeAudio').click(function () {
        alert('关闭直播');
        //todo
    });
    /**
     * 用户讨论区
     */
    discuss.init();
    var canvas = document.querySelector('#canvas'),
        context = canvas.getContext('2d');
    var width = 100,
        height = $(window).height() * .64;
    canvas.width = width;
    canvas.height = height;
    if (window.devicePixelRatio) {
        /*                canvas.style.width = width + "px";
         canvas.style.height = height + "px";
         canvas.height = height * window.devicePixelRatio;
         canvas.width = width * window.devicePixelRatio;
         context.scale(window.devicePixelRatio, window.devicePixelRatio);*/
    }
    var canvases = createCanvases();
    zan = new Zan(canvas, canvases, {});
    $('#zan').click(function () {
        zan.start();
    });
});
var discuss = {
    ul: '',
    status: '飞轮海 等6人正在去买',
    items: [
        {
            name: '周杰伦',
            message: '可以吃吗'
        },
        {
            name: '林心如',
            message: '有人用过没'
        },
        {
            name: '鹿晗',
            message: '有没有优惠'
        },
        {
            name: '小四',
            message: '感觉还行啊'
        },
        {
            name: '张杰',
            message: '要不然试试'
        }
    ],
    colors: ['FFF68F', 'FFB90F', 'FF8C00', 'FF4500', 'FF8247', 'EE82EE', 'EE3A8C', 'EE0000', 'DB7093', 'B23AEE'],
    addItem: function (name, message) {
        var color = this.colors[parseInt(Math.random() * this.colors.length, 10)];
        var li = '<li class="clear_fix"><p><span style="color\:#' + color + '">' + name + '</span>&nbsp;' + message + '</p></li>';
        this.ul.append(li);
        this.checkSize();
    },
    checkSize: function () {
        var ul = this.ul,
            lis = ul.find('li'),
            li = ul.find('li:first-child'),
            h = 0;
        lis.each(function () {
            var me = $(this);
            h += (me.height() + parseInt(me.css('margin-bottom')));
        });
        if (parseInt(ul.css('maxHeight')) < h) {
            li.remove();
            this.checkSize();
        }
    },
    addStatus: function (message) {
        if (!message) {
            return false;
        }
        var prev = $('#status h3');
        if (prev.length) {
            prev.addClass('remove');
            setTimeout(function () {
                prev.remove();
            }, 400);
        }
        $('#status').append('<h3><span class="no_wrap">' + message + '</span></h3>');
    },
    init: function () {
        var self = this;
        self.ul = $('#discuss');
        self.addStatus(self.status);
        self.items.forEach(function (val) {
            self.addItem(val.name, val.message);
        });
    }
};
function createCanvases() {
    var arr = [];
    for (var i = 1; i < 25; i++) {
        (function () {
            var img = new Image(),
                _canvas = document.createElement('canvas'),
                _context = _canvas.getContext('2d');
            img.src = 'static/images/zan/' + i + '.png';
            img.onload = function () {
                _context.drawImage(img, 0, 0, 30, 30);
                arr.push(_canvas);
            };
        })(i);
    }
    return arr;
}
function Zan(can, canvases, o) {
    var self = this;
    self.can = can;
    self.w = can.width;
    self.h = can.height;
    self.status = 0;                    //0-初始化、1-开始、2-停止、3-暂停、4-继续
    self.loop = null;                   //动画
    self.falls = [];                   //坠落物，包括叶子和果子
    self.images = [];                      //坠落物图片
    self.fallSpeed = o.fallSpeed;           //坠落速度
    self.disX = 500;                         //坠落物x坐标间距基数
    self.disY = 1;                         //坠落物y坐标间距
    self.items = 0;

    var context = can.getContext('2d');

    self.init = function () {
        self.status = 0;
        self.loop = null;
        self.falls = [];
    };

    self.createFalls = function () {
        var self = this;
        var rand = parseInt(Math.random() * 23) + 1,
            img = new Image();
        img.onload = function () {
            self.falls.push(new Fall(img));
            self.items += 1;
        };
        img.src = 'static/images/zan/' + rand + '.png';
    };

    self.draw = function () {
        var active = 0;
        context.clearRect(0, 0, self.w, self.h);
        for (var i = 0; i < self.falls.length; i++) {
            if (self.falls[i].show) {
                active++;
                self.falls[i].update(self);
                self.falls[i].render(context);
            }
        }
        if (active == 0) {
            self.stop();
        }
        self.loop = requestAnimationFrame(function () {
            self.draw();
        });
    };

    self.start = function () {
        self.pause();
        self.status = 1;
        self.createFalls();
        self.draw();
    };
    self.pause = function () {
        cancelAnimationFrame(self.loop);
    };
    self.resume = function () {
        if (self.status == 3) {
            self.status = 4;
            // 动画的计时控制
            self.loop = requestAnimationFrame(function () {
                self.draw();
            });
            self.down();
        }
    };
    self.stop = function () {
        if (this.status == 2) {
            return false;
        }
        self.pause();
        context.clearRect(0, 0, self.w, self.h);
    };

}
function Fall(img) {
    this.img = img;
    this.w = 30;
    this.h = 30;
    this.x = canvas.width / 2;	            //x坐标
    this.y = canvas.height - 30 / 2;	     //y坐标
    this.speed = Math.random() + 5;			    //坠落速度
    this.velY = 1.5;								//Y方向速度
    this.velX = Math.random() > .5 ? .5 : -.5;										//X方向速度
    this.disY = 3;
    this.alpha = 1;
    this.show = true;
}

Fall.prototype.update = function (zan) {
    this.velY += Math.random() / 200;

    this.y -= this.velY;
    if (this.alpha <= .5) {
        this.alpha -= .003;
    } else {
        this.alpha -= .005;
    }
    if (this.alpha <= .01) {
        this.alpha = .01;
    }
    if (this.x + this.w > zan.w) {
        this.velX -= Math.random() / 10;
    }
    if (this.x < 0) {
        this.velX += Math.random() / 10;
    }
    this.x += this.velX;
    // 飞出边界的处理
    if (this.y + this.h < 0) {
        this.show = false;
    }
};

Fall.prototype.render = function (context) {
    context.save();
    context.globalAlpha = this.alpha;
    context.drawImage(this.img, this.x, this.y, this.w, this.h);
    context.restore();
};
